import worker from '@ohos.worker';
import { Exchange, OperationType } from '../../workers/WorkerExchange';
import { Info } from './GyroscopeControl';

const workerThread = new worker.ThreadWorker('entry/ets/workers/RemoteWorker.ts');

export class RemoteControl {
  constructor() {
  }

  public init(successCallback: (str: string) => void, errorCallback: () => void, onConnectCallback: () => void) {
    let exchange = new Exchange(OperationType.create);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
      let result = event.data;
      if (result == "failed") {
        errorCallback();
      } else if (result == 'connected') {
        onConnectCallback();
      }
      else {
        successCallback(event.data);
      }
    }
  }

  public connect(str: string, successCallback: () => void, errorCallback: () => void) {
    let exchange = new Exchange(OperationType.connect, str);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
      let result = event.data;
      if (result == "failed") {
        errorCallback();
      } else {
        successCallback();
      }
    }
  }

  public setCallback(callback: (info: Info) => void, stopCallback: () => void) {
    workerThread.onmessage = (event) => {
      if (event.data == "close") {
        workerThread.onmessage = null;
        stopCallback();
        return;
      }
      let info = Info.fromObject(event.data);
      callback(info);
    }
  }

  public startGyroscope(successCallback: (info: Info) => void, close: () => void) {
    let exchange = new Exchange(OperationType.startGyroscope);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
      let result = event.data;
      if (result == "stop") {
        close();
      } else {
        let info = Info.fromObject(event.data);
        successCallback(info);
      }
    }
  }

  public closeGyroscope(successCallback: () => void, errorCallback: () => void) {
    let exchange = new Exchange(OperationType.stopGyroscope);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
      let result = event.data;
      if (result == "failed") {
        errorCallback();
      } else {
        successCallback();
      }
    }
  }

  public close(successCallback: () => void, errorCallback: () => void) {
    let exchange = new Exchange(OperationType.close);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
      let result = event.data;
      if (result == "failed") {
        errorCallback();
      } else {
        successCallback();
      }
    }
  }
}